<template>
  <div class="app-container">
    <!-- 步骤条 -->
    <el-steps :active="3" align-center finish-status="success" style="margin-bottom: 20px;">
      <el-step title="申请请假"></el-step>
      <el-step title="申请审批"></el-step>
      <el-step title="请假结果"></el-step>
    </el-steps>

    <div class="info-container">
      <!-- 基本信息（从老人表接口获取） -->
      <el-card class="basic-info-card">
        <h3>基本信息</h3>
        <ul class="info-list">
          <li><span class="label">单据编号</span><span class="value">{{ leaveInfo.businessId || '-' }}</span></li>
          <li><span class="label">老人姓名</span><span class="value">{{ elderlyInfo.name || '-' }}</span></li>
          <li><span class="label">老人身份证号</span><span class="value">{{ elderlyInfo.idCard || '-' }}</span></li>
          <li><span class="label">联系方式</span><span class="value">{{ elderlyInfo.contact || '-' }}</span></li>
          <li><span class="label">护理等级</span><span class="value">{{ elderlyInfo.levelName || '-' }}</span></li>
          <li><span class="label">入住床位</span><span class="value">{{ elderlyInfo.bedNo || '-' }}</span></li>
          <li><span class="label">护理员</span><span class="value">{{ elderlyInfo.caregiverNameStr || '-' }}</span></li>
        </ul>
      </el-card>

      <!-- 申请信息（从leave_request表接口获取） -->
      <el-card class="apply-info-card">
        <h3>申请信息</h3>
        <ul class="info-list">
          <li><span class="label">陪同人姓名</span><span class="value">{{ leaveInfo.companionName || '-' }}</span></li>
          <li>
            <span class="label">请假周期</span>
            <span class="value">{{ formatDateRange(leaveInfo.leaveStartTime, leaveInfo.expectedEndTime) || '-' }}</span>
          </li>
          <li>
            <span class="label">请假天数</span>
            <span class="value">{{ calculateLeaveDays(leaveInfo.leaveStartTime, leaveInfo.expectedEndTime) }}天</span>
          </li>
          <li><span class="label">请假原因</span><span class="value">{{ leaveInfo.leaveReason || '-' }}</span></li>
          <li><span class="label">申请人</span><span class="value">{{ userStore.nickName || '-' }}</span></li>
          <li><span class="label">申请时间</span><span class="value">{{ formatTime(leaveInfo.createTime) || '-' }}</span></li>
        </ul>
      </el-card>

      <!-- 销假记录（从leave_request表接口获取） -->
      <el-card class="return-record-card" v-if="leaveInfo.pizhun === '已返回'">
        <h3>销假记录</h3>
        <ul class="info-list">
          <li><span class="label">状态</span><span class="value">{{ leaveInfo.pizhun || '已返回' }}</span></li>
          <li><span class="label">实际返回时间</span><span class="value">{{ formatTime(leaveInfo.actualEndTime) || '-' }}</span></li>
          <li><span class="label">实际请假天数</span><span class="value">{{ leaveInfo.actualLeaveDays || '-' }}天</span></li>
          <li><span class="label">销假时间</span><span class="value">{{ formatTime(leaveInfo.actualEndTime) || '-' }}</span></li>
          <li><span class="label">备注</span><span class="value">{{ leaveInfo.actualReturnRemark || '-' }}</span></li>
        </ul>
      </el-card>
      <el-card class="no-return-card" v-else>
        <div class="no-return-text">暂无销假记录</div>
      </el-card>
    </div>

    <!-- 操作记录 -->
    <el-card class="operation-record-card">
      <h3>操作记录</h3>
      <ul class="record-list">
        <li class="record-item">
          <div class="record-info">
            <p>发起申请-申请请假</p>
            <p>{{ userStore.nickName || "当前用户" }}（已发起）</p>
          </div>
        </li>
        <li class="record-item">
          <div class="record-info">
            <p>(hulizuzhang) 审批-申请审批</p>
            <p>护理组组长 (审批中)</p>
          </div>
        </li>
      </ul>
    </el-card>

    <!-- 返回按钮 -->
    <div class="back-btn">
      <el-button @click="handleBack">返回列表</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
// 引入接口：请假记录（含申请和销假信息）、老人基本信息
import { getLeavemanage } from '@/api/leave/leavemanage';
import { getElderly } from '@/api/system/elderly';



import useUserStore from "@/store/modules/user";
// 2. 获取用户存储实例
const userStore = useUserStore();
// 3. 在脚本中打印用户信息
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});

const route = useRoute();
const router = useRouter();

// 请假记录信息（含申请信息和销假记录，来自leave_request表）
const leaveInfo = ref({});
// 老人基本信息（通过leave_request中的老人外键查询）
const elderlyInfo = ref({});
// 操作记录（实际项目可从接口获取，此处为模拟数据）
const operationRecords = ref([
  {
    operation: '发起申请-申请请假',
    operator: '顾廷烨',
    status: '已发起',
    time: '2048-10-15 09:00:00'
  },
  {
    operation: '护理主管审批-申请审批',
    operator: '盛明兰',
    status: '已通过',
    time: '2048-10-15 10:30:00'
  }
]);

// 计算请假天数（根据开始和结束时间）
const calculateLeaveDays = (startTime, endTime) => {
  if (!startTime || !endTime) return '-';
  const start = new Date(startTime);
  const end = new Date(endTime);
  if (isNaN(start.getTime()) || isNaN(end.getTime())) return '-';
  const timeDiff = end.getTime() - start.getTime();
  return Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 向上取整，跨天算1天
};

// 时间格式化（年月日 时分秒）
const formatTime = (time) => {
  if (!time) return '-';
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 格式化日期范围
const formatDateRange = (start, end) => {
  if (!start || !end) return '-';
  return `${formatTime(start)} 至 ${formatTime(end)}`;
};

// 获取请假记录详情（含申请信息和销假记录）
const getLeaveDetail = async (leaveId) => {
  try {
    const response = await getLeavemanage(leaveId);
    leaveInfo.value = response.data || {};
    // 从请假记录中获取老人外键，查询老人基本信息
    if (leaveInfo.value.elderlyId) { // 假设leave_request表中老人外键字段为elderlyId
      await getElderlyDetail(leaveInfo.value.elderlyId);
    } else {
      ElMessage.warning('未找到关联的老人信息');
    }
  } catch (error) {
    console.error('获取请假详情失败：', error);
    ElMessage.error('获取请假详情失败');
  }
};

// 根据老人ID查询基本信息   getElderly
const getElderlyDetail = async (elderlyId) => {
  try {
    const response = await getElderly(elderlyId);
    elderlyInfo.value = response.data || {};
  } catch (error) {
    console.error('获取老人信息失败：', error);
    ElMessage.error('获取老人信息失败');
  }
  console.log("获取老人信息",elderlyInfo);
  
};

// 页面初始化时加载数据
onMounted(() => {
  const { leaveId } = route.query;
  if (leaveId) {
    getLeaveDetail(leaveId); // 先获取请假记录，再通过老人外键查基本信息
  } else {
    ElMessage.warning('缺少请假记录ID');
    router.push('/leave/list'); // 跳转回列表页
  }
});

// 返回列表页
const handleBack = () => {
  router.back();
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.info-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.basic-info-card,
.apply-info-card,
.return-record-card,
.no-return-card,
.operation-record-card {
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

h3 {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 16px;
  color: #333;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

/* 修复红色虚线问题：确保边框为浅灰色虚线 */
.info-list li {
  border-bottom: 1px dashed #eee; /* 浅灰色虚线，避免红色 */
  padding-bottom: 8px;
}

.info-list li:last-child {
  border-bottom: none; /* 最后一项去除边框 */
}

.label {
  width: 120px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
  color: #333;
}

/* 销假记录样式 */
.no-return-card {
  text-align: center;
  padding: 30px 0;
}

.no-return-text {
  color: #999;
  font-size: 14px;
}

/* 操作记录样式 */
.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
  font-size: 14px;
}

.record-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #409eff;
  margin: 6px 10px 0 0;
}

.record-content {
  flex: 1;
  color: #333;
}

.record-content p {
  margin: 4px 0;
}

.record-time {
  width: 150px;
  text-align: right;
  color: #999;
}

/* 返回按钮 */
.back-btn {
  text-align: center;
  margin-top: 20px;
}
</style>